package com.ganxiang.ximenhong.model;

import android.content.Context;
import android.os.AsyncTask;

import org.json.JSONObject;

import java.net.HttpURLConnection;
import java.util.HashMap;

public class Task extends AsyncTask<String, Object, Object>{
	
	public static final String CALLBACK_TAG = "callback_tag";
	private TaskListener mTaskListener = null;
	public TaskType mTaskType = null;
	private HashMap<String, Object> mTaskParams = null;
	private Context mContext;
	private Object mTag;
	
	public Task(Context context, TaskListener listener, HashMap<String, Object> params){
		mContext = context;
		mTaskType = (TaskType) params.get("taskType");
		mTaskListener = listener;
		mTaskParams = params;
		mTag = params.get(CALLBACK_TAG);
	}
	
	public TaskListener getListener(){
		return mTaskListener;
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		if(mTaskListener != null){
			mTaskListener.taskStarted(mTaskType);
		}
	}
	
	@Override
	protected void onProgressUpdate(Object... values) {
		super.onProgressUpdate(values);
		if(mTaskListener != null){
			if(values[0] instanceof Integer){
				mTaskListener.taskProgress(mTaskType, (Integer)values[0], (Integer)values[1]);
			}
		}
	}
	
	public void runOnUI(Object... objs){
		publishProgress(objs);
	}
	
	public void cancelTask(){
		cancel(true);
		if(DataLoader.getInstance(mContext).getTaskMap().containsKey(mTaskType + "" + mTaskListener.hashCode()) && mTaskParams.containsKey("connection")){
			if(((HttpURLConnection)mTaskParams.get("connection")) != null){
				new Thread(){
					@Override
					public void run(){
						((HttpURLConnection)mTaskParams.get("connection")).disconnect();
					}
				}.start();
				if(mTaskListener != null){
					mTaskListener.taskIsCanceled(mTaskType);
				}
			}
			DataLoader.getInstance(mContext).getTaskMap().remove(mTaskType + "" + mTaskListener.hashCode());
		}
	}

	@Override
	protected Object doInBackground(String... params) {
		Object obj = null;
		obj = DataLoader.getInstance(mContext).getResult(mTaskParams, this, true);	
		if(obj != null){
			JSONObject jsObj = null;		
			if(obj instanceof JSONObject){
				jsObj = (JSONObject)obj;
			}			
			if(obj instanceof Error){
				System.out.println("result==="+((Error)obj).getMessage());
				return obj;
			}
			else{
				System.out.println("result==="+obj.toString());
			}		
		}
		return obj;
	}

	@Override
	protected void onPostExecute(Object result) {
		super.onPostExecute(result);
		if(mTaskListener != null){
			if(DataLoader.getInstance(mContext).getTaskMap().containsKey(mTaskType + "" + mTaskListener.hashCode())){
				DataLoader.getInstance(mContext).getTaskMap().remove(mTaskType + "" + mTaskListener.hashCode());		
				if(mTag != null){
					mTaskListener.taskFinished(mTaskType, result, mTag);
				}else {
					mTaskListener.taskFinished(mTaskType, result);
				}
				
			}
		}
	}
}
